package org.darkbits.cyklon.util;

public class Notes {
	private Notes() { }
	
	public static final int NOTE_A4 = 69;
	public static final float FREQUENCY_A4 = 440.0f;
	
	public static float noteToFrequency(float note) {
		return (float)(Math.pow(2.0, (note-NOTE_A4)/12.0) * FREQUENCY_A4);
	}
	
	public static float noteToFrequency(int note) {
		return (float)(Math.pow(2.0, (note-NOTE_A4)/12.0) * FREQUENCY_A4);
	}
	
	public static float frequencyToNote(float frequency) {
		return (float)(Math.log(frequency / FREQUENCY_A4) / Math.log(2) * 12 + NOTE_A4);
	}
	
	public static String noteName(int note) {
		int octave = (note / 12);
		switch (note % 12) {
		case 0:
			return "C-" + octave;
		case 1:
			return "C#" + octave;
		case 2:
			return "D-" + octave;
		case 3:
			return "D#" + octave;
		case 4:
			return "E-" + octave;
		case 5:
			return "F-" + octave;
		case 6:
			return "F#" + octave;
		case 7:
			return "G-" + octave;
		case 8:
			return "G#" + octave;
		case 9:
			return "A-" + octave;
		case 10:
			return "A#" + octave;
		case 11:
			return "B-" + octave;
		default: // Should never ever happen
			return null;
		}
	}
	
	public static String noteNameWithCents(float note) {
		int intnote = Math.round(note);
		int cents = Math.round((note - intnote) * 100.0f);
		String name = noteName(intnote);
		if (cents >= 0) {
			return name + " +" + cents + " ct";
		} else {
			return name + " " + cents + " ct";
		}
	}
}
